<template>
  <div>
    <!--    <el-button type="primary" @click="test">click</el-button>-->

    <!--    <el-cascader-->

    <!--        style="margin-left: 10px; width: 255px"-->
    <!--        placeholder="请选择单位"-->
    <!--        ref="dwref"-->
    <!--        v-model="dwval"-->
    <!--        @change="dwchange"-->
    <!--        :options="dwoptions"-->
    <!--        :props="{ expandTrigger: 'hover', checkStrictly: true, label: 'dwname', value:'id' }"-->
    <!--        clearable></el-cascader>-->


    <el-container>
      <el-aside class="operation_box" width="300px"
                style="margin-top: 0px; margin-left: 0px; border-right: 1px solid #ddd;">


        <!--        <el-input-->

        <!--            placeholder="输入关键字进行过滤"-->
        <!--            v-model="filterText">-->
        <!--        </el-input>-->

        <!--        :props="defaultProps"--><!--          default-expand-all  -->
        <el-tree
            class="tree"
            style="margin-top: 0px;"
            :data="dwoptions"
            node-key="id"
            :expand-on-click-node="false"
            :highlight-current="true"
            @current-change="currentchange2"
            :props="{  label: 'dwname' }"
            :default-expanded-keys="dwtree_expand_keys"
            @node-expand="handleExpand"
            @node-collapse="handleCollapse"
            ref="tree">
        </el-tree>

      </el-aside>
      <el-container style="margin-left: 100px">


        <el-main>
          <div style="margin-top: 0px; margin-left: 20px; font-size: 14px">
            开机：<span
              style="display: inline-block;margin-right: 10px; width: 14px; height:14px;background-color: green; color: red; border-radius: 50%"></span>
            停机：<span
              style="display: inline-block;margin-right: 10px; width: 14px; height:14px;background-color: darkgray; color: red; border-radius: 50%"></span>
            故障：<span
              style="display: inline-block; width: 14px; height:14px;background-color: red; color: red; border-radius: 50%"></span>
          </div>
          <div>
            <el-select style="margin-left: 20px" v-model="gx" clearable placeholder="请选择干线" filterable
                       @change="gxchange">
              <el-option
                  v-for="item in gxArr"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
              </el-option>
            </el-select>

            <el-input style="width: 200px; margin: 0 20px" placeholder="请输入井号" suffix-icon="el-icon-search"
                      v-model="jh"/>

            <el-button type="primary" @click="search" icon="el-icon-search">搜索</el-button>

            <!--            <el-button round icon="el-icon-warning-outline" type="danger" style="margin: 10px 80px"-->
            <!--                       @click="showbathTjConfirmForm">-->
            <!--              批量停机-->
            <!--            </el-button>-->
            <el-button round icon="el-icon-warning-outline" type="danger" style="margin: 10px 80px"
                       @click="showWSbathTjConfirmForm">
              批量停机
            </el-button>
<!--            <el-image :src="require('@/assets/avatar1.jpg')" style="width: 100%; height: 100%; margin: 10px 0px"></el-image>-->

            <el-dialog width="40%" title="停机确认！" :visible.sync="stopConfirmdialogFormVisible">
              <div>
              <el-image :src="require('@/assets/safe.png')" style="float: left; width: 10%; height: 10%; margin-right: 50px"></el-image>
              <span style="display: block;  color: red; font-size: 18px"> 涉及重大安全，请谨慎操作！</span>
              <span style="display: block; color: red; font-size: 18px" > 请在操作前按照安全操作规程确认设备周边环境安全！ </span>
              </div>
              <el-divider ><i class="el-icon-bell"></i></el-divider>
              <span style="display: block;  font-size: 18px">
              确定要对 {{ stopform.jh }}井 进行停机操作吗？</span>
              <div slot="footer" class="dialog-footer">
                <el-button @click="stopConfirmdialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="stopCyj()">确 定</el-button>
              </div>
            </el-dialog>

            <el-table ref="table" @selection-change="handleSelectionChange" :data="tableData"
                      style="margin: 20px;" border stripe :span-method="arraySpanMethod">
              <el-table-column width="50" type="selection">
              </el-table-column>
              <el-table-column prop="id" label="ID" width="60" v-if="false">
              </el-table-column>
              <el-table-column sortable prop="jh" label="井号" width="120">
                <template slot-scope="scope">
                  <span
                      v-if="scope.row.state == 1"
                      style="display: inline-block;  width: 18px; height:18px;background-color: green;  border-radius: 50%">

                  </span>
                  <span
                      v-if="scope.row.state == 2"
                      style="display: inline-block; width: 20px; height:20px;background-color: darkgray;  border-radius: 50%">
                  </span>
                  <span
                      v-if="scope.row.state == 0"
                      style="display: inline-block; width: 20px; height:20px;background-color: red;  border-radius: 50%">
                  </span>
                  {{scope.row.jh}}
                </template>
              </el-table-column>
              <el-table-column prop="ip" label="IP" width="180" v-if="false">
              </el-table-column>
              <el-table-column sortable prop="dwObj.dwname" label="所属单位" width="180">
              </el-table-column>
              <el-table-column sortable prop="gxObj.name" label="所属干线" width="180">
              </el-table-column>
<!--              <el-table-column prop="role.roleName" label="启停状态" width="100" >-->
<!--                <template slot-scope="scope">-->
<!--                  <span-->
<!--                      v-if="scope.row.state == 1"-->
<!--                      style="display: inline-block; width: 20px; height:20px;background-color: green;  border-radius: 50%">-->
<!--                  </span>-->
<!--                  <span-->
<!--                      v-if="scope.row.state == 2"-->
<!--                      style="display: inline-block; width: 20px; height:20px;background-color: darkgray;  border-radius: 50%">-->
<!--                  </span>-->
<!--                  <span-->
<!--                      v-if="scope.row.state == 0"-->
<!--                      style="display: inline-block; width: 20px; height:20px;background-color: red;  border-radius: 50%">-->
<!--                  </span>-->
<!--                </template>-->
<!--              </el-table-column>-->
              <el-table-column prop="#" label="远程停机">
                <template slot-scope="scope">
                  <el-button round type="danger" icon="el-icon-switch-button" @click="showConfirmForm(scope.row)">停机
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <!--            <div>-->
            <!--              <el-button round icon="el-icon-warning-outline" type="danger" style="margin: 10px"-->
            <!--                         @click="showbathTjConfirmForm">-->
            <!--                批量停机-->
            <!--              </el-button>-->
            <!--            </div>-->
            <el-dialog width="20%" title="停机确认！" :visible.sync="batchstopConfirmdialogFormVisible">
              预计最大耗时{{ timeout / 1000 }}s,确定要批量停机吗？
              <div v-for="(item, index) in selectedRows"> {{ item.jh }}</div>
              <div slot="footer" class="dialog-footer">
                <el-button @click="batchstopConfirmdialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="batchstopCyj()">确 定</el-button>
              </div>
            </el-dialog>
            <el-dialog width="40%" title="批量停机确认！" :visible.sync="WSbatchstopConfirmdialogFormVisible">
              <div>
                <el-image :src="require('@/assets/safe.png')" style="float: left; width: 10%; height: 10%; margin-right: 50px"></el-image>
                <span style="display: block;  color: red; font-size: 18px"> 涉及重大安全，请谨慎操作！</span>
                <span style="display: block; color: red; font-size: 18px" > 请在操作前按照安全操作规程确认设备周边环境安全！ </span>
              </div>
              <el-divider ><i class="el-icon-bell"></i></el-divider>
              <div style="font-size: 18px">
                预计最大耗时{{ timeout / 1000 }}秒,确定要批量停机吗？
                <div v-for="(item, index) in selectedRows"> {{ item.jh }}</div>
              </div>
              <div slot="footer" class="dialog-footer">
                <el-button @click="WSbatchstopConfirmdialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="WSbatchstopCyj()">确 定</el-button>
              </div>
            </el-dialog>
            <div class="block" style="padding: 5px">

              <el-pagination

                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page="currentPage"
                  :page-sizes="[10, 20, 50, 100,500,1000]"
                  :page-size="pageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total">
              </el-pagination>
            </div>
          </div>
        </el-main>

      </el-container>
    </el-container>

  </div>

</template>
<script>
import service from "@/utils/request";
import ElementUI from "element-ui";


import VueRouter from 'vue-router'
import HomeView from "@/views/HomeView.vue";


export default {
  created() {
    service.get('/dw/getAll', {}).then(
        response => {
          if (response.data.code == 20000) {
            this.dwoptions = response.data.data
          } else {
            this.$message.error(response.data.message)
          }
        }, error => {
          ElementUI.Message({
            message: error.message,
            type: 'error'
          })
        }
    )
    service.get('/gx/getAll', {}).then(
        response => {
          if (response.data.code == 20000) {
            this.gxArr = response.data.data;
          } else {
            this.$message.error(response.data.message)
          }
        }, error => {
          ElementUI.Message({
            message: error.message,
            type: 'error'
          })
        }
    )
    this.load();
  },
  data() {
    return {
      timeout: 2000, //批量停机超时初始值 2000ms

      dwoptions: [],
      dwval: [],
      dwtree_expand_keys: [1],

      jh: '',
      gx: null,
      gxArr: [],
      tableData: [],
      selectedRows: [], // 用来存储选中行的数据
      pageSize: 10,
      total: 100,
      currentPage: 1,
      dialogFormVisible: false,
      stopConfirmdialogFormVisible: false,
      batchstopConfirmdialogFormVisible: false,
      WSbatchstopConfirmdialogFormVisible: false,
      // form: {
      //   username: '',
      //   password: '',
      //   roleId: '',
      // },
      stopform: {
        id: null,
        jh: '',
        ip: '',
        dw: ''
      },
      formLabelWidth: '120px'
    }
  },
  methods: {
    test() {
      console.log(this.treeval)
      // service.get('/dj/test', {}).then(
      //     response => {
      //       if (response.data.code == 20000) {
      //
      //         this.$message.success(response.data.message)
      //       }
      //     }
      // )

    },

    load() {

      // service.get('/dj/getlist', {
      //   params: {
      //     jh: this.jh,
      //     dw: this.dwval,
      //     // dw: this.dwval[this.dwval.length - 1],
      //     gx: this.gx
      //   }
      // }).then(response => {
      //       if (response.data.code == 20000) {
      //         this.tableData = response.data.data;
      //       }
      //     },
      //     error => {
      //       ElementUI.Message({
      //         message: error.message,
      //         type: 'error'
      //       })
      //     }
      // );
      service.get('/dj/getpageBydwgxjh', {
        params: {
          dw: this.dwval,
          gx: this.gx,
          jh: this.jh,
          pagesize: this.pageSize,
          pagenum: this.currentPage,
        }
      }).then(response => {
            if (response.data.code == 20000) {
              this.tableData = response.data.data.records;
              this.total = response.data.data.total;
              this.currentPage = response.data.data.current;
              this.pageSize = response.data.data.size;
              for (let i = 0; i < this.tableData.length; i++) {
                this.$set(this.tableData[i], 'state', 1) // 1 :开机，2：停机，0： 故障
                //获取停开机状态 ,未实现！！-----------------------
                // getState(this.tableData[i].jh)
                // service.get('/dj/getStateByjh', {params: {jh: this.tableData[i].jh}}).then(
                //     response => {
                //     },
                //     error=>{
                //
                //     }
                // )
                //未实现------------------------------------
              }
            }
          },
          error => {
            ElementUI.Message({
              message: error.message,
              type: 'error'
            })
          }
      );
    },

    handleExpand(data) {
      if (!this.dwtree_expand_keys.includes(data.id)) {
        this.dwtree_expand_keys.push(data.id)
      }
    },
    handleCollapse(data) {
      if (this.dwtree_expand_keys.includes(data.id)) {
        this.dwtree_expand_keys.splice(this.dwtree_expand_keys.indexOf(data.id), 1)
      }
    },
    //currentchange1 是对 currentchange   的精简改进
    currentchange(nodedata, node) {

      this.gx = null;

      service.get('/dw/getPathByid', {params: {id: nodedata.id}}).then(
          response => {
            if (response.data.code == 20000) {
              let dwpath = response.data.data;
              this.dwval = dwpath
              return dwpath
            } else {
              this.$message.error(response.data.message)
              throw response.data.message
            }
          }
      ).then(
          response => {
            let dw = response
            if (dw.length > 0) {
              let dwTmp = dw[0]
              if (dw.length > 1) {
                dwTmp = dw[1]
              }
              // service.get('/gx/getlistbydw', {params: {dwid: dw[dw.length - 1]}}).then(
              service.get('/gx/getlistbydw', {params: {dwid: dwTmp}}).then(
                  response => {
                    if (response.data.code == 20000) {
                      this.gxArr = response.data.data;
                      this.load()
                    } else {
                      this.$message.error(response.data.message)
                    }
                  }, error => {
                    ElementUI.Message({
                      message: error.message,
                      type: 'error'
                    })
                  }
              )
            } else {
              service.get('/gx/getAll', {}).then(
                  response => {
                    if (response.data.code == 20000) {
                      this.gxArr = response.data.data;
                      this.load()
                    } else {
                      this.$message.error(response.data.message)
                    }
                  }, error => {
                    ElementUI.Message({
                      message: error.message,
                      type: 'error'
                    })
                  }
              )
            }
          }
      )
    },


    //currentchange1 是对 currentchange   的精简改进
    currentchange1(nodedata, node) {
      this.gx = null;
      service.get('/dw/getPathByid', {params: {id: nodedata.id}}).then(
          response => {
            if (response.data.code == 20000) {
              let dwpath = response.data.data;
              this.dwval = dwpath
              let dw = dwpath//dw多余，可以直接用dwpath但是不改了！
              if (dw.length > 0) {
                let dwTmp = dw[0]
                if (dw.length > 1) {
                  dwTmp = dw[1]
                }
                // service.get('/gx/getlistbydw', {params: {dwid: dw[dw.length - 1]}}).then(
                return service.get('/gx/getlistbydw', {params: {dwid: dwTmp}})
              } else {
                return service.get('/gx/getAll', {})
              }
            } else {
              // this.$message.error(response.data.message)
              throw new Error(response.data.message)
            }
          }
      ).then(
          response => {
            if (response.data.code == 20000) {
              this.gxArr = response.data.data;
              this.load()
            } else {
              // this.$message.error(response.data.message)
              throw new Error(response.data.message)
            }
          }
      ).catch(
          error => {
            // this.$alert('dfdfd')
            this.$message.error(error.message)
          }
      )
    },

    //上面的2各函数currentchange1 ,currentchange 逻辑不对，下面的函数是对上面的2个函数的修正。
    async currentchange2(nodedata, node) {
      this.gx = null;
      this.dwval = nodedata.id
      service.get('/gx/getlistbydw1', {params: {dwid: nodedata.id}}
      ).then(
          response => {
            if (response.data.code == 20000) {
              this.gxArr = response.data.data;
              this.load()
            } else {
              throw new Error(response.data.message)
            }
          }
      ).catch(
          error => {
            this.$message.error(error.message)
          }
      )
    },

    nodeclick(nodedata, node, com) {
    }
    ,

    filterNode() {

    }
    ,
    dwchange(dw) {
      // console.log(dw)
      this.gx = null;
      if (dw.length > 0) {
        let dwTmp = dw[0]
        if (dw.length > 1) {
          dwTmp = dw[1]
        }
        // service.get('/gx/getlistbydw', {params: {dwid: dw[dw.length - 1]}}).then(
        service.get('/gx/getlistbydw', {params: {dwid: dwTmp}}).then(
            response => {
              if (response.data.code == 20000) {
                this.gxArr = response.data.data;
                this.load()
              } else {
                this.$message.error(response.data.message)
              }
            }, error => {
              ElementUI.Message({
                message: error.message,
                type: 'error'
              })
            }
        )
      } else {
        service.get('/gx/getAll', {}).then(
            response => {
              if (response.data.code == 20000) {
                this.gxArr = response.data.data;
                this.load()
              } else {
                this.$message.error(response.data.message)
              }
            }, error => {
              ElementUI.Message({
                message: error.message,
                type: 'error'
              })
            }
        )
        // this.gxArr = []
      }
    }
    ,

    gxchange(gxval) {
      this.load()
    }
    ,
    handleSelectionChange(selection) {
      // console.log(selection)
      // this.selectedRows = selection.map(row => row._row);
      this.selectedRows = selection
      // console.log(this.selectedRows)
    }
    ,
    WSbatchstopCyj() {
      this.WSbatchstopConfirmdialogFormVisible = false
      //this.selectedRows
      let msg = {}
      msg.type = 'batchstop'
      msg.data = this.selectedRows
      let msgStr = JSON.stringify(msg)
      this.$store.dispatch('sendWebSocketMessage', msgStr)

    },
    batchstopCyj() {
      this.batchstopConfirmdialogFormVisible = false
      service.post('/dj/batchtj', this.selectedRows, {
        timeout: this.timeout
      }).then(response => {
            if (response.data.code == 20000) {
              // this.$message.success('批量发送停机命令成功，请及时确认停机状态!');
              // this.load()
              this.$alert(response.data.data, '批量停机成功！', {
                type: 'success',
                callback: action => {
                  this.batchstopConfirmdialogFormVisible = false
                },
                confirmButtonText: '确定',
              });
            } else {
              // this.$message.error(response.data.message)
              this.$alert(response.data.message, '批量停机错误！', {
                type: 'error',
                callback: action => {
                  this.batchstopConfirmdialogFormVisible = false
                },
                confirmButtonText: '确定',
              });
            }
          }, error => {
            // console.log(error.code == ECONNABORTED)
            if (error.code == "ECONNABORTED") {
              this.$alert(' 操作超时，请及时检查抽油机状态!', '停机错误！', {
                type: 'error',
                callback: action => {
                  this.batchstopConfirmdialogFormVisible = false
                },
                confirmButtonText: '确定',
              })
              // ElementUI.Message({
              //   message: error.message,
              //   type: 'error'
              // })
            }
          }
      )
    }
    ,

    stopCyj() {
      this.stopConfirmdialogFormVisible = false
      service.post('/dj/tj', this.stopform).then(response => {
        if (response.data.code == 20000) {
          // this.$message.success('发送停机命令成功，请及时确认停机状态!');
          // this.load()
          this.$alert(this.stopform.jh + '停机成功', '成功', {
            confirmButtonText: '确定',
            type: 'success',
            callback: action => {
              // this.$message({
              //   type: 'success',
              //   message: `action: ${ action }`
              // });
            }
          });
        } else {
          // this.$message.error(response.data.message)
          this.$alert(this.stopform.jh + '停机失败，' + response.data.message, '错误', {
            confirmButtonText: '确定',
            type: 'error',
            callback: action => {
              // this.$message({
              //   type: 'error',
              //   message: `action: ${ action }`
              // });
            }
          });
        }
      }, error => {
        ElementUI.Message({
          message: error.message,
          type: 'error'
        })
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.load()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.load()
    },

    showConfirmForm(row) {
      this.id = row.id
      this.stopform.jh = row.jh
      this.stopform.ip = row.ip
      this.stopform.dw = row.dw
      this.stopConfirmdialogFormVisible = true
    }
    ,
    showWSbathTjConfirmForm() {
      if (this.selectedRows.length == 0) {
        this.$alert('请选择停机抽油机!', '停机错误！', {
          type: 'error',
          callback: action => {
            this.batchstopConfirmdialogFormVisible = false
          },
          confirmButtonText: '确定',
        });
        return
      }
      if (this.selectedRows.length > 100) {
        this.$alert('请不要选择超过100台抽油机!', '停机错误！', {
          type: 'error',
          callback: action => {
            this.batchstopConfirmdialogFormVisible = false
          },
          confirmButtonText: '确定',
        });
        return
      }
      this.timeout = 5000;
      this.timeout += this.selectedRows.length * 500;
      this.timeout += Math.floor(this.selectedRows.length / 20) * 5000;
      this.WSbatchstopConfirmdialogFormVisible = true
    },
    showbathTjConfirmForm() {
      if (this.selectedRows.length == 0) {
        this.$alert('请选择停机抽油机!', '停机错误！', {
          type: 'error',
          callback: action => {
            this.batchstopConfirmdialogFormVisible = false
          },
          confirmButtonText: '确定',
        });
        return
      }
      if (this.selectedRows.length > 100) {
        this.$alert('请不要选择超过100台抽油机!', '停机错误！', {
          type: 'error',
          callback: action => {
            this.batchstopConfirmdialogFormVisible = false
          },
          confirmButtonText: '确定',
        });
        return
      }
      this.timeout = 5000;
      this.timeout += this.selectedRows.length * 500;
      this.timeout += Math.floor(this.selectedRows.length / 20) * 5000;
      this.batchstopConfirmdialogFormVisible = true
    },
    search() {
      // this.currentPage = 1
      this.load()
    },
    // handleDelBatch() {
    //   console.log(this.$route)
    // },
    arraySpanMethod({row, column, rowIndex, columnIndex}) {
    }
  }
}
</script>
<style scoped>
/deep/ .el-tree-node__content {
  height: 40px;
}

/deep/ .el-tree-node__label {
  font: bold 16px/1.5 "Microsoft YaHei";
}
</style>
